package cn.sat.miniodemo.test;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MinioExample {
    private static final Logger log = LoggerFactory.getLogger(MinioExample.class);

    public static void main(String[] args) throws FileNotFoundException {
        // 1. 创建 MinIO 客户端
        String endpoint = "http://127.0.0.1:9090"; // MinIO 服务地址
        String accessKey = "root";      // 替换为你的 Access Key
        String secretKey = "123456789";      // 替换为你的 Secret Key

        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        // 2. 定义要上传的文件和目标存储桶及对象名称
        String bucketName = "root";           // 存储桶名称
        String objectName = "MinioConfiguration.java";    // 对象名称（在 MinIO 中的文件名）
        String filePath = "E:\\minIoDemo\\src\\main\\java\\cn\\sat\\miniodemo\\config\\MinioConfiguration.java"; // 本地文件路径
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        try {
            // 3. 检查存储桶是否存在，如果不存在则创建
            boolean isBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isBucketExists) {
                // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                System.out.println("Bucket created: " + bucketName);
            } else {
                System.out.println("Bucket already exists: " + bucketName);
            }

            // 4. 上传文件到 MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(fis, file.length(), -1)
                    .build()
            );

            System.out.println("File uploaded successfully to: " + bucketName + "/" + objectName);
        } catch (Exception e) {
            log.info("Error: ", e);
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
                log.info("Error: ", e);
            }
        }
    }
}